import axios from "axios";
import qs from "qs";

// 创建axios的实例
const instance = axios.create({
  baseURL: "http://127.0.0.1:5000", // 请求的基路径
  timeout: 5000, // 请求超时时间
});

instance.interceptors.request.use(
  (config) => {
    // 对所有请求做统一处理（给鉴权接口添加鉴权字段）
    const token = JSON.parse(localStorage.getItem("t_k"));
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (err) => {
    console.error(err);
  }
);

instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (err) => {
    console.error(err);
  }
);

// 创建基于restful接口规范的异步请求方法
const get = async (url, params = {}) => {
  return await instance.get(url, { params });
};

const post = async (url, data) => {
  return await instance.post(url, qs.stringify(data));
};

// PUT请求方法
const put = async (url, data) => {
  return await instance.put(url, qs.stringify(data));
};

// DELETE请求方法
const del = async (url, params = {}) => {
  return await instance.delete(url, { params });
};

export default {
  get,
  post,
  put,
  del,
};
